package it.alb.calcolatrice;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.preference.PreferenceManager;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.TextView;
import android.widget.Toast;

import com.example.calcolatrice.R;

public class Utility extends Activity{
	
	
	private final static int PORT_NUMCHAR = 16;
	private final static int LAND_NUMCHAR = 32;
	private final static int WIDTH = 384;
	public static boolean calcolo = false;
	public static int parAperta = 0;
	public static int parChiusa = 0;
			
	@SuppressWarnings("deprecation")
	public static void setBackground(View mainActivity, Context ctx, Resources res){
		SharedPreferences settings;
		settings = PreferenceManager.getDefaultSharedPreferences(ctx);
        String sfondo = settings.getString("bkg_img", "noImg");
	    Drawable draw = new BitmapDrawable(res, BitmapFactory.decodeFile(sfondo));
	    if (!draw.equals(null) && !sfondo.equals("noImg")){
	    	mainActivity.setBackgroundDrawable(draw);
	    } else {
	    	mainActivity.setBackgroundDrawable(null);
	    	mainActivity.setBackgroundColor(Color.parseColor("#000000"));
	    }
    }
	
	public static boolean setResultType (Context ctx){
		SharedPreferences settings;
		settings = PreferenceManager.getDefaultSharedPreferences(ctx);
		return settings.getBoolean("splitCalc", false);
	}
	
	public static void calcola(String expression, TextView display, Context ctx) throws NumberFormatException{
        Double temp = 0.0;
        String result = "";
        String[] tmp;
        if (expression.contains(",")){
        	expression = expression.replace(",", ".");
        }
			if (control(expression, R.id.uguale ) == 1) {
	               if (expression.contains("√")) {
	                      expression = expression.replace("√", "sqrt");
	               }
	               org.nfunk.jep.JEP parser = new org.nfunk.jep.JEP();
	               parser.addStandardFunctions();
	               parser.addVariable("x", 0);
	               parser.parseExpression(expression);
	               temp = parser.getValue();
	               result = temp.toString();
	               if (result != "Infinity") {
		               tmp = result.split("\\.");
		               Double n2 = Double.parseDouble(tmp[1]);
		               if (Double.valueOf(n2) == 0){
		            	   result = (tmp[0]);
		               }else if (result.contains(".")){
		            	   result = result.replace(".", ",");
		               }
		               display.setText(result);
		               calcolo = true;
	               } else {
	            	   Toast toast = Toast.makeText(ctx, "Infinito: calcolo non consentito!", Toast.LENGTH_LONG);
	            	   toast.setGravity(Gravity.CENTER, 0, 0);
	            	   toast.show();
	            	   calcolo = true;
	               }
	        }
	}
	
	public static int control(String test, int id){
		if (id == R.id.virgola || id == R.id.uguale) {
			if (!test.endsWith(".") && !test.endsWith("+") && !test.endsWith("-")
					&& !test.endsWith("*") && !test.endsWith("/") && !test.endsWith("^") && !test.equals("") && !test.endsWith("√(")
					&& !test.endsWith("(")){
				return 1;
			}
		}else if (id == R.id.somma || id == R.id.sottrazione || id == R.id.prodotto || id == R.id.divisione || id == R.id.chiudiPar
				  || id == R.id.potenza) {
			if (test.endsWith(".") || test.endsWith("+") || test.endsWith("-") || test.endsWith("*") || test.endsWith("(")
					|| test.endsWith("/") || test.endsWith("^") || test.endsWith("√(") || test.equals("")) {
				return 2;
			}else {
				return 1;
			}
			
		}else if (id == R.id.apriPar) {
			if (!test.endsWith("(")){
				return 3;
			}
		}
		
		return 0;
	}
	
	/**
	 * @param test
	 * @param operatore
	 * @param display
	 * @param id
	 * @param operatoreCorrente
	 * @param numero
	 */
	public static void controlOperatore(String test, String operatore, TextView display, int id, String operatoreCorrente, String numero){
		String risultato = display.getText().toString();
		if (id == R.id.divisione && id == R.id.potenza && id == R.id.prodotto && id == R.id.somma && id == R.id.sottrazione) {
			if (Utility.control(test, id) == 2) {
				String tmp = risultato.substring(risultato.lastIndexOf(operatore.toString()));
				if (tmp.equals(operatore.toString())) {
					tmp = tmp.replace(operatore, operatoreCorrente);
					if (!operatore.equals("√(")) {
						if (Utility.control(risultato.substring(0, risultato.length()-1), id) == 1) {
							display.setText(risultato.substring(0, risultato.length()-1) + tmp);
						}
					}else {
						if (Utility.control(test, id) == 1) {
							display.setText(risultato.substring(0, risultato.length()-2) + tmp);
						}
					}
				}
			}
		} else if (id == R.id.apriPar || id == R.id.radq) {
			if(!risultato.equals("")) {
				String tmp = risultato.substring(risultato.lastIndexOf(numero));
				if (tmp.equals(numero.toString())) {
					display.setText(test + "*"+ operatore);
				}else{
					display.setText(test + operatore);
				}
			}else {
				display.setText(test + operatore);
			}
		} else if (id == R.id.zero || id == R.id.uno || id == R.id.due || id == R.id.tre || id == R.id.quattro 
				|| id == R.id.cinque || id == R.id.sei || id == R.id.sette || id == R.id.otto || id == R.id.nove) {
			if (test.endsWith(")")) {
				display.setText(test + "*");
			} else if (operatore.equals("=")) {
				display.setText(test);
			}
		} 
	}
	
	
	public static int contaParAperte(String test, char c){
		int lng = test.length();
        if( test.length() == 0) {
           return 0;
        }
        else {
        	if (test.charAt(0) == c) {
        		parAperta = 1;
        	}
	        for (int k=0; k<lng - 1; k++) {
	       		test = test.substring(1);
	       		if (test.charAt(0) == c)
	       			parAperta = parAperta + 1;
	       	}
        }
        return parAperta;
	}
	
	
	public static int contaParChiuse(String test, char c){
		int lng = test.length();
        if( test.length() == 0) {
           return 0;
        }
        else {
        	for (int k=0; k<lng - 1; k++) {
        		test = test.substring(1);
        		if (test.charAt(0) == c)
        			parChiusa = parChiusa + 1;
        	}
        }
        return parChiusa;
	}
	
	public static void formattaCarattere(View view){
		String test = "";
		TextView display = (TextView) view;
		test = (String) display.getText();
		if (test.length() >= PORT_NUMCHAR) {
			display.setTextSize(27);
		}else if (test.length() < PORT_NUMCHAR){
			display.setTextSize(36);
		}
	}
	
	/**
	 * Rotate = 1; Translate = 2; Rotate&Translate=3
	 * @param v
	 * @param screenWidth
	 * @param sceltaAnim
	 * @param option
	 */
	public static void animation (View v, int screenWidth, int sceltaAnim, boolean option) {
		Animation animation;
		Animation animation2;
		int x=screenWidth;
		x-=v.getWidth()+v.getLeft();
		if (option == true){		
			switch (sceltaAnim){
			
			case 1:
				animation= new RotateAnimation(0, 1800,Animation.RELATIVE_TO_SELF, 0.5f,Animation.RELATIVE_TO_SELF, 0.5f);
				animation.setDuration(350);
				animation.setFillAfter(false);
				v.startAnimation(animation);
				break;
				
			case 2:
				animation= new TranslateAnimation(Animation.ABSOLUTE, 0, Animation.ABSOLUTE, x, Animation.ABSOLUTE,  0, Animation.ABSOLUTE, 0);
				animation.setDuration(2000);
				animation.setFillAfter(true);
				v.startAnimation(animation);
				break;
				
			case 3:
				AnimationSet animSet=new AnimationSet(false);
				animation= new RotateAnimation(0, 45,Animation.RELATIVE_TO_SELF, 0.5f,Animation.RELATIVE_TO_SELF, 0.5f);
				animation.setDuration(2000);
				animation.setFillAfter(true);
				animSet.addAnimation(animation);
				animation2= new TranslateAnimation(Animation.ABSOLUTE, 0, Animation.ABSOLUTE, x, Animation.ABSOLUTE,  0, Animation.ABSOLUTE, 0);
				animation2.setDuration(2000);
				animation2.setFillAfter(true);
				animSet.addAnimation(animation2);
				v.startAnimation(animSet);
				break;
			
			default:
				break;
			}
		}

	}
	
	public static boolean controlAnim (Context ctx) {
		SharedPreferences settings;
		settings = PreferenceManager.getDefaultSharedPreferences(ctx);
		return settings.getBoolean("anim", false);
	}
	
	
//	public static void controlRisultato (String test) {
//		
//	}
//	
	
//	public static boolean controlLettera(String regex, String test){
//		Pattern pattern = Pattern.compile(regex);
//		Matcher matcher = pattern.matcher(test);
//
//		while (matcher.find()) {
//		    return true;
//		}
//		    return false;
//		} 
}
